<!-- 采购单生成 -->
<template>
  <div>
    <cus-search style="padding-bottom: 0;">
      <cus-search-item>
        <Form :model="selectForm" :label-width="80" ref="formValidate" @keydown.native.enter.prevent="onInit">
          <FormItem label="食材名称" class="mr_48 mb_20" prop="materialName">
            <Input placeholder="请输入食材名称" maxlength="20" clearable v-model="selectForm.materialName" />
          </FormItem>
          <FormItem label="食材种类" class="mr_48 mb_20" prop="dishType">
            <Select v-model="selectForm.dishType" transfer clearable placeholder="全部" style="width: 195px">
              <Option :value="''">全部</Option>
              <Option v-for="item in materialTypeList" :value="item.name" :key="item.name">
                {{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="采购来源" class="mr_48 mb_20" prop="type">
            <Select transfer clearable v-model="selectForm.type" placeholder="全部" style="width: 195px">
              <Option :value="''">全部</Option>
              <Option :value="0">导入</Option>
              <Option :value="1">食谱</Option>
            </Select>
          </FormItem>
          <cusButton class="ml_20 mb_20" type="primary" @onClick="
            pages.page = 1;
          postApiFoodBookServiceGetPurchasingInfoByIdDtlApi();
          " v-permission="10">查询</cusButton>
          <cusButton class="ml_20 mb_20" type="primary" @onClick="reset()" v-permission="10">重置</cusButton>
        </Form>
      </cus-search-item>
    </cus-search>
    <cus-card :showTitle="false" class="cardBox mt_20">
      <div class="btnBox">
        <div class="btnBox-item">
          <cusButton class="mr_20" type="primary" v-if="selectData.length != 10" @onClick="handleSelectAll(true)" ghost>全选
          </cusButton>
          <cusButton class="mr_20" type="primary" v-if="selectData.length != 0" @onClick="handleSelectAll(false)" ghost>{{
            selectData.length == 10 ? '取消全选' : '取消所选' }}</cusButton>
          <cusButton class="mr_20" type="error" :disabled="selectData.length == 0" ghost @onClick="onDeleteSelect()">删除
          </cusButton>
        </div>
        <div class="btnBox-item">
          <cusButton type="primary" @onClick="importExcel()" v-permission="50" style="width:150px;">导入</cusButton>
        </div>
      </div>
      <cusTable border ref="cusTable" :loading="form.loading" :columns="columns" :bottomClass="bottomList" :data="data"
        :size="vuex_config.tableSize" @on-selection-change="changeSelect" @on-select-all="changeSelectAll"
        @on-select-all-cancel="changeSelectAllCancel">
        <template slot-scope="{ row, index }" v-for="(item, idx) in weeks" :slot="item">
          <div>
            <InputNumber v-if="!row.isEdit" :max="100000" :min="0" :value="row[item].weight" @on-change="value => {
              changeNum(index, item, value);
            }
              " style="width: 80px" />
            <div v-else>
              {{ row[item].weight }}
            </div>
          </div>
        </template>
        <template slot-scope="{ row, index }" slot="operation">
          <div class="flex">
            <cus-button type="text" size="small" v-if="row.isEdit" :style="{ color: '#1E6FFF' }" style="padding: 0 5px"
              @onClick="onEdit(row, index)">
              <Icon type="md-color-filter" size="4" style="margin: 2px 5px 0 0" />
              <span>编辑</span>
            </cus-button>
            <cus-button type="text" size="small" v-if="!row.isEdit" :style="{ color: '#1E6FFF' }" style="padding: 0 5px"
              @onClick="onSave(index)">
              保存
            </cus-button>
            <cus-button type="text" size="small" v-if="!row.isEdit" :style="{ color: '#1E6FFF' }" style="padding: 0 5px"
              @onClick="reduction">
              取消
            </cus-button>
            <cus-button type="text" size="small" :style="{ color: '#FF4746' }" style="padding: 0 5px"
              @onClick="onDelete(row)">
              <Icon type="md-trash" size="4" style="margin: 2px 5px 0 0" />
              <span>删除</span>
            </cus-button>
          </div>
        </template>
      </cusTable>
      <div class="cus_page">
        <cus-page :data="pages" @pageChange="postApiFoodBookServiceGetPurchasingInfoByIdDtlApi()"></cus-page>
      </div>
    </cus-card>
    <!--底部返回-->
    <div class="cus_operBox" v-if="data.length > 0" style="z-index: 1001;width: calc(100% - 250px)">
      <Button type="error" class="mr_24" @click="onNext()">下一步</Button>
    </div>
    <!-- 导入 -->
    <cus-uploadModal ref="cusUploadModal" :showUpload="false" :temp-src="getApiPurchasingDownloadPurchasingSummaryExcel"
      titleName="导入采购计划"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" @onOk="onInit">
      <template v-slot:right>
        <Card style="height: 220px; width: 170px; cursor: pointer" @click.native="importExcelChange()">
          <div class="draw-section-item-logo flex mt_10">
            <svg t="1628043694436" class="icon" viewBox="0 0 1157 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
              p-id="24667" width="118" height="118">
              <path
                d="M0.09216 582.528c0-124.37504 82.23744-233.71264 192.1536-266.112C253.07648 156.0832 403.70688 40.96 579.93216 40.96c177.64352 0 324.18304 115.07712 384.96768 275.456 113.4336 33.152 192.19968 141.06624 192.19968 266.112 0 153.96864-119.57248 279.14752-270.91968 279.14752-28.34432 0-53.92896-26.60864-53.92896-56.06912 0-33.8176 25.58464-56.1152 53.92896-56.1152 91.22816 0 163.80928-74.09664 163.80928-166.87616 0-49.61792-21.44768-95.67744-56.64768-125.1328l-9.66144-9.43616a48.96256 48.96256 0 0 0-12.46208-10.05568c-2.75968-3.60448-9.03168-3.60448-12.46208-6.49728h-3.42528c-2.75968-3.5584-6.23104-3.5584-9.0368-6.4512h-3.47136c-2.75968 0-6.23104-3.5584-9.65632-3.5584-2.75968 0-6.23104 0-6.23104-2.8928h-9.0368c-3.47136 0-6.23104 0-9.7024-3.60448h-25.4976c-2.75968-10.81344-6.23104-18.688-6.23104-29.50144-2.75968 0-2.75968-3.5584-2.75968-6.4512-3.42528-6.49728-3.42528-12.90752-6.23104-19.44576 0-3.5584-3.42528-3.5584-3.42528-7.16288-2.75968-6.49728-6.23104-12.90752-9.65632-19.4048v-6.49728c-2.80576-6.4512-9.07776-12.90752-12.46208-19.44576-53.18144-92.11392-151.38816-154.63936-261.97504-154.63936-113.34144 0-211.46624 62.5664-264.68864 154.63936l-9.0368 19.44576c0 2.18112-1.42336 2.18112-2.08896 4.31616l-1.3824 2.18112-9.7024 19.4048v7.16288l-8.94464 19.44576v6.4512c-3.47136 10.77248-6.94272 18.688-6.94272 29.46048h-28.30336c-2.75968 3.60448-6.23104 3.60448-8.94464 3.60448h-6.23104c-2.75968 2.18112-4.14208 2.8928-4.89472 2.8928a1.24928 1.24928 0 0 1-2.048 0c-2.75968 0-6.23104 3.5584-9.03168 3.5584h-6.23104c-3.42528 2.93376-6.23104 2.93376-9.65632 6.49728h-3.42528c-2.75968 2.8928-6.23104 2.8928-9.07776 6.49728h-3.42528c-2.75968 3.5584-6.23104 6.4512-9.7024 10.05568-6.23104 2.84672-8.94464 6.49728-12.416 9.39008-35.24608 29.50656-53.2224 75.56096-53.2224 125.17888 0 92.77952 72.58112 166.87616 160.37888 166.87616 32.4864 0 56.69376 22.29248 56.69376 56.06912 0 29.50656-24.20736 56.07424-56.69376 56.07424-147.82976 0.04096-270.8736-125.13792-270.8736-279.01952v-0.09216z"
                p-id="24668"></path>
              <path
                d="M362.94656 566.72768c0-16.54784 6.23104-28.78976 12.46208-39.56224l163.7632-186.90048c10.41408-10.81344 24.91904-16.55296 40.8064-16.55296 15.92832 0 28.34432 5.7856 41.47712 16.512l160.37888 186.98752c21.5296 22.19008 21.00224 57.63072-1.18784 79.16544a56.00256 56.00256 0 0 1-39.57248 15.80032c-15.92832 0-27.67872-8.6784-38.04672-19.45088l-69.10976-78.40768v281.9584c0 33.8176-24.21248 55.3984-53.93408 55.3984-31.104 0-53.2224-21.5808-53.2224-55.3984v-281.91232L457.69728 602.7264c-10.368 10.81344-25.54368 19.45088-41.43104 19.45088-28.3904 0-53.31456-25.90208-53.31456-55.40352v-0.04608z"
                p-id="24669"></path>
            </svg>
          </div>
          <div class="title">采购单文件上传</div>
          <div class="label">可拖拽上传</div>
        </Card>
      </template>
    </cus-uploadModal>
    <!-- 导入采购计划条件选择框-->
    <Modal v-model="modal" title="导入采购计划" width="520" @on-ok="ok" @on-cancel="cancel">
    </Modal>
    <!--导入采购需求汇总-->
    <importExcel ref="importExcel" @onCancel="uploadModalOnCancel()"></importExcel>
    <!--下一步生成供应商采购清单前效验错误提示-->
    <excelErrorModal ref="excelErrorModal">
      <template v-slot:footer>
        <div class="modal-footer">
          <cus-button size="small" class="mr_2" @onClick="onCancel()">{{ errorModalOk ? '取消' : '关闭' }}</cus-button>
          <cus-button v-if="errorModalOk" type="primary" size="small" @onClick="onOk()">确认</cus-button>
        </div>
      </template>
    </excelErrorModal>
  </div>
</template>

<script>
import {
  getApiFoodBookServiceGetPurchasingPlanId,
  getBasicMaterialType,
  postApiFoodBookServiceGetPurchasingInfoByIdDtl,
  postApiFoodBookServiceUpdatePurchasingPlanRecord,
  getApiPurchasingDownloadPurchasingSummaryExcel,
  postApiFoodBookServiceDelPurchasingRecord,
  postApiFoodBookServiceDelPurchasingFoodExamine,
  postApiFoodBookServiceAuditConfirmPurchasingPlan,
  deleteAllPurchasingRecord,
} from "@/api/business/manager";
import importExcel from "./components/importExcel.vue";
import excelErrorModal from "./components/excelErrorModal.vue";

const form = {
  id: "",
  goodId: "", // 食谱id
  materialName: "", // 食材名称
  dishType: "", // 食材种类
  type: "", // 采购来源
  goodName: "", // 食谱原料名称
  sum: "", // 合计
  unit: "", // 单位
  planDtlDays: [] // 上传上周日-周一修改后的采购需求
};
const selectForm = {
  id: "",
  materialName: "", // 食材名称
  dishType: "", // 食材种类
  type: "" // 采购来源
};
const columns = [
  {
    type: 'selection',
    width: 60,
    fixed: "left",
    align: 'center'
  },
  {
    title: "序号",
    type: "index",
    width: 70,
    fixed: "left",
    align: "center"
  },
  {
    title: "食材种类",
    minWidth: 125,
    key: "materialClass",
    fixed: "left",
    align: "center"
  },
  {
    title: "食材名称",
    minWidth: 125,
    key: "goodName",
    fixed: "left",
    align: "center"
  },
  {
    title: "商品名称",
    minWidth: 125,
    key: "productMaterialName",
    align: "center"
  },
  {
    title: "计量单位",
    minWidth: 125,
    key: "unit",
    align: "center"
  },
  {
    title: "上周日",
    minWidth: 125,
    slot: "lastSunday",
    align: "center"
  },
  {
    title: "周一",
    minWidth: 125,
    slot: "one",
    align: "center"
  },
  {
    title: "周二",
    minWidth: 125,
    slot: "two",
    align: "center"
  },
  {
    title: "周三",
    minWidth: 125,
    slot: "three",
    align: "center"
  },
  {
    title: "周四",
    minWidth: 125,
    slot: "four",
    align: "center"
  },
  {
    title: "周五",
    minWidth: 125,
    slot: "five",
    align: "center"
  },
  {
    title: "周六",
    minWidth: 125,
    slot: "six",
    align: "center"
  },
  {
    title: "周日",
    minWidth: 125,
    slot: "sunday",
    align: "center"
  },
  {
    title: "合计",
    minWidth: 125,
    key: "sum",
    align: "center",
    render: (h, params) => {
      return h("div", [h("span", params.row.sum)]);
    }
  },
  {
    title: "采购来源",
    minWidth: 125,
    align: "center",
    render: (h, params) => {
      return h("div", [h("span", params.row.type == 0 ? "导入" : "食谱")]);
    }
  },
  {
    title: "操作",
    minWidth: 145,
    fixed: "right",
    slot: "operation",
    align: "center"
  }
];
export default {
  name: "puchaseGeneration",
  components: { importExcel, excelErrorModal },

  data() {
    return {
      bottomList: ['cus-page'],
      loading: false,
      planId: null, // 食谱id
      form,
      data: [],
      selectForm,
      columns: columns,
      weeks: [
        "lastSunday",
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
        "sunday"
      ],
      materialTypeList: [], // 食材种类Select数据
      modal: false, // 导入Excel文件框
      getApiPurchasingDownloadPurchasingSummaryExcel, //excel下载地址
      errorModalOk: true,
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0
      },
      selectData: [], // 选中数据
      selectStatu: false, //全选状态
      selectMaterialId: [], //勾选Id
      tableHeight: 0
    };
  },
  mounted() {
    setTimeout(() => {
      this.tableHeight = window.innerHeight - 430; // 表格自适应高度
    }, 100);
    window.addEventListener("resize", this.tableHeightChange, true);
    this.onInit();
    this.selectForm = {};
  },
  destroyed() {
    window.removeEventListener("resize", this.tableHeightChange, true);
  },
  updated() { },
  methods: {
    // 设置Table表头高度自适应
    tableHeightChange() {
      this.tableHeight = 0;
      setTimeout(() => {
        this.tableHeight = window.innerHeight - 430; // 表格自适应高度
      }, 100);
    },
    onInit() {
      this.getBasicMaterialTypeApi();
      this.getApiFoodBookServiceGetPurchasingPlanIdApi();
    },
    reset() {
      this.$refs["formValidate"].resetFields();
      this.postApiFoodBookServiceGetPurchasingInfoByIdDtlApi();
    },
    // 选中全选表格选项变化
    changeSelectAll(e) {
      this.selectStatu = true
    },
    // 取消选中全选
    changeSelectAllCancel(e) {
      this.selectStatu = false
    },
    // 表格选项变化
    changeSelect(e) {
      console.log(e)
      console.log('zzz',this.selectMaterialId);
      this.selectData = e
      if (this.selectData.length == 0) {
        this.selectStatu = false
        return
      }
      let state = this.selectData.every((item) => {
        return (
          this.selectMaterialId.includes(item.id) &&
          this.selectData.length == this.selectMaterialId.length
        )
      })
      // console.log(state);
      this.selectStatu = state
    },
    handleSelectAll(status) {
      this.selectStatu = !this.selectStatu;
      this.$refs["cusTable"].tableDom(status);
    },
    // 批量删除勾选数据
    onDeleteSelect() {
      if (!this.selectData.length) {
        this.$Message.warning('请先选择要删除的数据内容.')
      } else {
        this.$Modal.confirm({
          title: '删除确认',
          content: `是否确认删除选中数据内容？`,
          onOk: () => {
            this.deleteAllPurchasingRecordApi()
          }
        })
      }
    },
    // 批量删除采购信息
    deleteAllPurchasingRecordApi() {
      return new Promise((resolve) => {
        let planIdDtls = this.selectData.map((item) => item.id)
        deleteAllPurchasingRecord({
          planIdDtls: planIdDtls
        }).then((res) => {
          if (res.retCode === 2000) {
            this.$Message.success('供应信息删除成功.')
            // 删除成功后清空选中列表
            this.selectData = []
            if (this.pages.page > 1) {
              this.pages.page--
            }
            this.onInit()
            resolve()
          }
        })
      })
    },
    // 导入组件
    importExcel() {
      console.log('导入');
      this.$refs["cusUploadModal"].show();
    },
    // 导入选择条件框
    uploadTemp() {
      this.modal = true;
    },
    ok() { },
    cancel() { },
    // 编辑
    onEdit(row, index) {
      console.log(row);
      this.$set(this.data[index], "isEdit", !this.data[index].isEdit);
      this.form = JSON.parse(JSON.stringify(row));
    },
    // 保存
    onSave(index) {
      let arr = [];
      this.weeks.forEach(item => {
        this.data[index][item].weight = this.data[index][item].weight;
        console.log(this.data[index][item]);
        arr.push(this.data[index][item]);
      });
      this.form.planDtlDays = arr;
      this.postApiFoodBookServiceUpdatePurchasingPlanRecordApi();
    },
    // 还原
    reduction() {
      this.postApiFoodBookServiceGetPurchasingInfoByIdDtlApi();
    },
    // 修改数额
    changeNum(index, key, value) {
      this.$set(this.data[index][key], "weight", value);
    },
    //删除
    onDelete(row) {
      this.$cu
        .dialog({
          params: row
        })
        .then(({ id }) => {
          this.postApiFoodBookServiceDelPurchasingRecordApi(id);
        });
    },
    //导入采购需求
    importExcelChange() {
      this.$refs["importExcel"].show();
    },
    //下一步
    onNext() {
      if (this.data.length > 0) {
        this.postApiFoodBookServiceDelPurchasingFoodExamineApi();
      } else {
        this.$Message.error("未找到食谱采购需求");
      }
    },
    onOk() {
      this.postApiFoodBookServiceAuditConfirmPurchasingPlanApi(1);
    },
    onCancel() {
      this.$refs["excelErrorModal"].onCancel();
    },
    // 关闭上传excel框
    uploadModalOnCancel() {
      this.$refs["cusUploadModal"].onCancel();
    },
    //获取原料分类-----------------接口
    getBasicMaterialTypeApi() {
      return new Promise(resolve => {
        getBasicMaterialType().then(res => {
          if (res.retCode == 2000) {
            this.materialTypeList = res.data;
            resolve();
          }
        });
      });
    },
    //查询获取食谱PlanId在获取采购单生成列表数据--------------接口
    getApiFoodBookServiceGetPurchasingPlanIdApi() {
      return new Promise(resolve => {
        getApiFoodBookServiceGetPurchasingPlanId().then(res => {
          if (res.retCode == 2000) {
            this.planId = res.data; //获取采购计划id
            this.postApiFoodBookServiceGetPurchasingInfoByIdDtlApi();
            resolve();
          }
        });
      });
    },
    // 采购单生成列表数据---------------------------------接口
    postApiFoodBookServiceGetPurchasingInfoByIdDtlApi() {
      return new Promise(resolve => {
        let params = {
          planId: this.planId,
          materialName: this.selectForm.materialName,
          dishType: this.selectForm.dishType,
          type: this.selectForm.type,
          current: this.pages.page,
          size: this.pages.pageSize
        };
        postApiFoodBookServiceGetPurchasingInfoByIdDtl(params).then(res => {
          if (res.retCode == 2000) {
            this.selectMaterialId = []
            res.data.records.forEach(item => {
              item.isEdit = true;
              item.planDtlDays.forEach(it => {
                it.weight = it.weight;
                item[it.week] = it;
              });
              this.selectMaterialId.push(item.id);
            });
            this.data = res.data.records;
            console.log(this.selectMaterialId)
            this.bottomList = this.data.length ? ['cus-page', 'cus_operBox'] : ['cus-page']
            this.$nextTick(() => {
              this.$refs["cusTable"].getHeight();
            });
            this.pages.pageTotal = res.data.total;
            resolve();
          }
        });
      });
    },
    // 保存更改采购单需求---------------------------接口
    postApiFoodBookServiceUpdatePurchasingPlanRecordApi() {
      return new Promise(resolve => {
        let params = {
          goodId: this.form.goodId,
          goodName: this.form.goodName,
          id: this.form.id,
          planDtlDays: this.form.planDtlDays,
          purchasingPlanId: this.planId,
          sum: this.form.sum,
          unit: this.form.unit,
          type: this.form.type
        };
        postApiFoodBookServiceUpdatePurchasingPlanRecord(params).then(res => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            this.onInit();
          }
          resolve();
        });
      });
    },
    //删除----------------------------------------接口
    postApiFoodBookServiceDelPurchasingRecordApi(id) {
      return new Promise(resolve => {
        postApiFoodBookServiceDelPurchasingRecord({
          plandtlId: id
        }).then(res => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            this.postApiFoodBookServiceGetPurchasingInfoByIdDtlApi();
          }
          resolve();
        });
      });
    },
    //下一步生成供应商采购清单前效验---------------接口
    postApiFoodBookServiceDelPurchasingFoodExamineApi() {
      this.$cu.showLoading();
      return new Promise(resolve => {
        postApiFoodBookServiceDelPurchasingFoodExamine({
          purchasingPlanId: this.planId
        }).then(res => {
          if (res.retCode == 2000) {
            this.postApiFoodBookServiceAuditConfirmPurchasingPlanApi();
          } else if (res.retCode == 2888) {
            this.$cu.hideLoading(1);
            if (res.data != null && res.data != []) {
              this.errorModalOk = true
              this.$refs["excelErrorModal"].show();
              this.$refs["excelErrorModal"].data = res.data;
            }
          } else {
            this.$cu.hideLoading(1);
            if (res.data != null && res.data != []) {
              this.errorModalOk = false
              this.$refs["excelErrorModal"].show();
              this.$refs["excelErrorModal"].data = res.data;
            }
          }
          resolve();
        });
      });
    },
    //下一步生成供应商采购清单--------------------------接口
    postApiFoodBookServiceAuditConfirmPurchasingPlanApi(nextStep, type) {
      return new Promise(resolve => {
        let params = {
          nextStep: nextStep || 0,
          planId: this.planId,
          type: type || 0
        };
        postApiFoodBookServiceAuditConfirmPurchasingPlan(params).then(res => {
          this.$cu.hideLoading(1);
          if (res.retCode == 2000) {
            this.$router.push({
              name: "查看供应商采购列表",
              query: {
                planId: this.planId
              }
            });
            this.$refs["excelErrorModal"].onCancel();
          } else {
            if (
              res.data.length != 0 &&
              res.data != [] &&
              res.data != null &&
              res.data != undefined
            ) {
              this.$refs["excelErrorModal"].show();
              this.$refs["excelErrorModal"].title =
                "存在未供应食材,请确认是否继续生成采购单?";
              this.$refs["excelErrorModal"].data = res.data.food;
            }
          }
          resolve();
        });
      });
    }
  },
  watch: {},
  computed: {}
};
</script>

<style lang="less" scoped>
.operBox {
  position: fixed;
  bottom: 0;
  right: 0;
  height: 88px;
  display: flex;
  flex-direction: row-reverse;
  // width: 100%;
  background: #ffffff;
  align-items: center;
  padding: 0 40px;
  box-shadow: 0px -1px 6px 0px rgba(0, 0, 0, 0.12),
    0px -1px 2px -2px rgba(0, 0, 0, 0.16);
}

.cardBox {
  box-shadow: 0px 4px 8px 0px rgba(108, 137, 165, 0.18);
  padding: 20px 20px;
}

.btnBox {
  padding-bottom: 20px;
  width: 100%;
  display: flex;
  justify-content: space-between;

  &-item {
    display: flex;
  }
}

.title {
  text-align: center;
  margin-top: 10px;
  color: rgba(51, 51, 51, 1);
}

.label {
  text-align: center;
  color: rgba(153, 153, 153, 1);
}
</style>
